import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import localCache from '@/utils/cache'
import { useStore } from '@/store'
import { defaultMenu, mapMenus2Routes } from '@/utils/map-menus'
import store from '@/store'

const routes: RouteRecordRaw[] = [
  { path: '/', redirect: 'main' },
  { path: '/login', name: 'login', component: () => import('@/views/login/login.vue') }, // 这里使用 import 是懒加载的方式
  { path: '/main', name: 'main', component: () => import('@/views/main/main.vue') },
  { path: '/:pathMatch(.*)*', name: 'not-foundx', component: () => import('@/views/not-found/not-found.vue') }
]

const router = createRouter({
  routes,
  history: createWebHashHistory()
})

// 导航守卫
router.beforeEach((to) => {
  if (to.path !== '/login') {
    const token = localCache.getCache('token')
    const userInfo = localCache.getCache('userInfo')
    if (!token || !userInfo) {
      return '/login'
    }
  }

  const userMenus = (store.state as any).login.userMenus
  const routes = mapMenus2Routes(userMenus)

  routes.forEach((route) => {
    router.addRoute('main', route)
  })

  if (to.path === '/main') {
    return defaultMenu.url
  }
})

export default router
